
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import java.io.File;
import java.io.FileReader;
import java.lang.Exception;
import java.lang.String;
import java.nio.CharBuffer;
import java.security.PrivilegedAction;

/**
 java -Djava.security.manager -Djava.security.policy==policy.txt -Djava.security.auth.login.config==example.conf MyClient
 */
public class MyClient {
  public static void main(String argv[]) {
    LoginContext ctx = null;
    try {
      ctx = new LoginContext("WeatherLogin", new MyCallbackHandler());
    } catch(LoginException le) {
      System.err.println("LoginContext cannot be created. "+ le.getMessage());
      System.exit(-1);
    } catch(SecurityException se) {
      System.err.println("LoginContext cannot be created. "+ se.getMessage());
    }
    try {
      ctx.login();
    } catch(LoginException le) {
     System.out.println("Authentication failed. " + le.getMessage());
     System.exit(-1);
    }
    System.out.println("Authentication succeeded.");
    Subject subject = ctx.getSubject();
    Subject.doAsPrivileged(subject, new PrivilegedAction() {
      @Override
      public Object run() {
        File file = new File("max.txt");
//        System.out.println(file.getAbsolutePath());
//        System.out.println(new File(".").listFiles()[0].getAbsolutePath());
        if (file.exists()) {
          try {
            char[] chars = new char[100];
            FileReader reader = new FileReader(file);
            int limit = reader.read(chars);
            System.out.println(CharBuffer.wrap(chars,0,limit).toString());
          }catch (Exception ignore){
          }
          System.out.println("The file exists in the current working directory");
        } else {
          System.out.println("The file does not exist in the current working directory");
        }
        return null;
      }
    }, null);
    try {
      ctx.logout();
    } catch (LoginException le) {
      System.out.println("Logout: " + le.getMessage());
    }
  }
}
